package conf

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"gopkg.in/yaml.v2"
)

// ModelPath model保存路径
const ModelPath = "./models/"

// ModelReplace 是否覆盖已存在model
const ModelReplace = true

// DriverName 数据库驱动
const DriverName = "mysql"

type DbConf struct {
	Host   string `yaml:"Host"`
	Port   string `yaml:"Port"`
	User   string `yaml:"User"`
	Pwd    string `yaml:"Pwd"`
	DbName string `yaml:"DbName"`
}

type Config struct {
	DBInfo DbConf   `yaml:"DbConf"`
	Tables []string `yaml:"Tables"`
}

// Con 数据库链接配置
var (
	Con Config

	saveConfigFlag bool = false
)

func promptConfig() Config {
	reader := bufio.NewReader(os.Stdin)

	// Host
	fmt.Print("Enter database host (default localhost): ")
	host, _ := reader.ReadString('\n')
	host = strings.TrimSpace(host)
	if host == "" {
		host = "localhost"
	}

	// Port
	fmt.Print("Enter database port (default 3306): ")
	port, _ := reader.ReadString('\n')
	port = strings.TrimSpace(port)
	if port == "" {
		port = "3306"
	}

	// User
	fmt.Print("Enter database user (default root): ")
	user, _ := reader.ReadString('\n')
	user = strings.TrimSpace(user)
	if user == "" {
		user = "root"
	}

	// Password
	fmt.Print("Enter database password: ")
	pwd, _ := reader.ReadString('\n')
	pwd = strings.TrimSpace(pwd)
	if pwd == "" {
		pwd = "password"
	}

	// Database name
	fmt.Print("Enter database name (default testdb): ")
	dbName, _ := reader.ReadString('\n')
	dbName = strings.TrimSpace(dbName)
	if dbName == "" {
		dbName = "testdb"
	}

	// save config to file
	fmt.Print("Enter save config to file flag (default n (y/n)): ")
	flagStr, _ := reader.ReadString('\n')
	flagStr = strings.TrimSpace(flagStr)
	if flagStr != "" && flagStr == "y" {
		saveConfigFlag = true
	}

	return Config{
		DBInfo: DbConf{
			Host:   host,
			Port:   port,
			User:   user,
			Pwd:    pwd,
			DbName: dbName,
		},
		Tables: []string{},
	}
}

func saveConfig(config Config) error {
	file, err := os.Create("config.yaml")
	if err != nil {
		return err
	}
	defer file.Close()

	encoder := yaml.NewEncoder(file)
	return encoder.Encode(config)
}

func askUseConfigFile() bool {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Config file exists, use it? (y/n): ")
	answer, _ := reader.ReadString('\n')
	answer = strings.TrimSpace(strings.ToLower(answer))
	return answer == "y" || answer == "yes"
}

func init() {
	// Check if config file exists
	if _, err := os.Stat("config.yaml"); os.IsNotExist(err) {
		// File doesn't exist, prompt for config
		Con = promptConfig()
		if saveConfigFlag {
			if err := saveConfig(Con); err != nil {
				log.Fatalf("Failed to save config: %v", err)
			}
		}
		log.Println("Config file created at config.yaml")
	} else {
		// File exists, ask user
		if askUseConfigFile() {
			// Load config from file
			file, err := os.Open("config.yaml")
			if err != nil {
				log.Fatalf("Failed to open config file: %v", err)
			}
			defer file.Close()

			decoder := yaml.NewDecoder(file)
			if err := decoder.Decode(&Con); err != nil {
				log.Fatalf("Failed to decode config: %v", err)
			}
		} else {
			// User chose not to use config file, prompt for new config
			Con = promptConfig()
			if saveConfigFlag {
				if err := saveConfig(Con); err != nil {
					log.Fatalf("Failed to save config: %v", err)
				}
			}
		}
	}
	log.Printf("Con=%v", Con)
}
